package com.mlm.mlmapp.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.adapter.view.AQProgressDialog;
import com.mlm.mlmapp.adapter.view.BuyPartnerDialog;
import com.mlm.mlmapp.adapter.view.BuyPointsDialog;
import com.mlm.mlmapp.adapter.view.ParterDialog;
import com.mlm.mlmapp.adapter.view.listener.DialogListener;
import com.mlm.mlmapp.cons.Constants;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;
import com.mlm.mlmapp.utils.PayResult;
import com.mlm.mlmapp.wxapi.WXPayEntryActivity;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.Receiver;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

@EActivity(R.layout.show_web_view)
@SuppressLint("SetJavaScriptEnabled")
public class ShowWebView extends BaseActivity {
    @Pref
    Prefs_ pref;
    @Extra
    String url = "";
    @Extra
    String title = "";
    @Extra
    String mobile = "";
    //private Button button;
    private WebView webView;
    WebChromeClient wvcc;
    BuyPartnerDialog dialog;
    private AQuery aq;
    private String outtradeno;
    String type;
    String firstTitle = "";
    private Handler handler = new Handler();
    // 首先在您的Activity中添加如下成员变量
    final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    private SocializeListeners.SnsPostListener snsPostListener;

    @AfterViews
    void init() {

        Intent intent = getIntent();
        aq = new AQuery(this);
        url = intent.getStringExtra("url");
        wvcc = new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (firstTitle.equals(""))
                    firstTitle = title;
                ((TextView) findViewById(R.id.tv_title)).setText(title);
            }

        };
        if(title!=null&&!title.equals("")){
            ((TextView) findViewById(R.id.tv_title)).setText(title);
        }
        webView = (WebView) findViewById(R.id.webView1);
        if (haveNetworkConnection()) {
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    startWebView(url);
//                }
//            });
            startWebView(url);

        } else {
//           webView.loadUrl("file:///android_asset/error.html");
            webView.loadUrl("file:///android_asset/error.html");

        }
    }

    private void startWebView(String url) {


        // 设置setWebChromeClient对象
        if(!title.equals("详情")){
            webView.setWebChromeClient(wvcc);
        }else{
            firstTitle=title;
        }


        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                    startActivity(intent);
                } else {

                    Log.d("sort", "url" + url);

                    view.loadUrl(url);

                }
                return true;
            }

        });

        webView.setSaveEnabled(false);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new WebScriptInterface(), "share");
        webView.addJavascriptInterface(new WebScriptInterface(), "pay");
        webView.addJavascriptInterface(new WebScriptInterface(), "partner");
        webView.loadUrl(url);

    }


    @Click
    void btn_back() {
        onBackPressed();
    }

    @Override
    // Detect when the back button is pressed
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
            if (webView.canGoBack()) {
                webView.goBack();
            }
            if (!webView.canGoBack()) {
                ((TextView) findViewById(R.id.tv_title)).setText(firstTitle);
            }
        } else {
            // Let the system handle the back button
            super.onBackPressed();
            Intent data = new Intent();
            setResult(RESULT_CANCELED, data);
            Intent intent = new Intent();
            intent.setAction("point_refresh");
            aq.getContext().sendOrderedBroadcast(intent, null);
            this.finish();

        }
    }

    void pointNotify(String type) {
        if (type.equals(WXPayEntryActivity.WECHAT_PAY_SUCCESS)) {
            type = "2";
        } else {
            type = "1";
        }
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", mobile));
        pairs.add(new BasicNameValuePair("payType", type));
        String url;

        CommonUtils.postRequest(partner_notify, aq,
                new AjaxCallback<JSONObject>() {
                    @Override
                    public void callback(String url, JSONObject obj,
                                         AjaxStatus status) {
                        if (status.getCode() == -101) {
                            Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                                    Toast.LENGTH_SHORT);
                            return;
                        }
                        if (status.getCode() == -103) {
                            Toast.makeText(aq.getContext(), "用户信息异常，请联系客服",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            if (status.getCode() != 200) {
                                Toast.makeText(aq.getContext(),
                                        "网络异常:" + status.getCode(),
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                webView.reload();
                                try {
                                    if (obj.getBoolean("isSuccess")) {
                                    } else {
                                        Toast.makeText(aq.getContext(),
                                                obj.getString("errors"),
                                                Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                }, pairs);
    }

    @Receiver(actions = WXPayEntryActivity.PAY_FINISH, registerAt = Receiver.RegisterAt.OnCreateOnDestroy)
    protected void onPayFinish(Intent intent) {
//        dialog.dismiss();
        String state = intent.getStringExtra("state");
        if (state != null) {

            if (state.equals(WXPayEntryActivity.ALI_PAY_SUCCESS) || state.equals(WXPayEntryActivity.WECHAT_PAY_SUCCESS)) {
                Toast.makeText(this, "支付成功",
                        Toast.LENGTH_SHORT).show();
                showAlertDialog();
                pointNotify(state);

            } else {
                Toast.makeText(this, "支付失败",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void update() {
        AjaxCallback<JSONObject> cb = new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() == -103) {
                    Toast.makeText(aq.getContext(), "网络异常",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (status.getCode() != 200) {
                    Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
                            Toast.LENGTH_SHORT).show();
                } else {
                    pref.edit().proxyID().put(CommonUtils.getJsonString(html,
                            "proxyInfoId")).apply();

                }
            }
        };
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
        // pairs.add(new BasicNameValuePair("mobile", "18245189375"));

        CommonUtils.postRequest(get_user_info_action, aq, cb, pairs);
    }

    public void showAlertDialog() {

        ParterDialog.Builder builder = new ParterDialog.Builder(this);
        builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                update();
                dialog.dismiss();

            }
        });

        builder.create().show();

    }
    ActionSheetDialog actionSheetDialog;
    private class WebScriptInterface {
        @JavascriptInterface
        public void SharePartner() {
//        Toast.makeText(mContext, "JsCallAndroid", Toast.LENGTH_SHORT).show();
            handler.post(new Runnable() {
                public void run() {
                    snsPostListener = new SocializeListeners.SnsPostListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onComplete(SHARE_MEDIA platform, int stCode,
                                               SocializeEntity entity) {
                            if (stCode == 200) {
                                Toast.makeText(ShowWebView.this, "分享成功", Toast.LENGTH_SHORT)
                                        .show();
                            } else {
                            }
                        }
                    };
                    mController.registerListener(snsPostListener);
                    //默认分享列表中存在的平台如果需要删除，则调用下面的代码：
                    mController.getConfig().removePlatform(SHARE_MEDIA.TENCENT);
                    configPlatforms();
                    setShareContent();
                    mController.openShare(ShowWebView.this, false);

                }
            });
        }
        @JavascriptInterface
        public void saveImage(final String codeUrl){
            handler.post(new Runnable() {
                public void run() {
                    final AjaxCallback<File> cb = new AjaxCallback<File>() {
                        @Override
                        public void callback(String url, File file, AjaxStatus status) {
                            try {
                                Log.d("sort",file.getName());
                                MediaStore.Images.Media.insertImage(ShowWebView.this.getContentResolver(),
                                        file.getPath(), file.getName(), "");
                                Log.d("sort",file.getPath());
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }

                            MediaScannerConnection.scanFile(ShowWebView.this, new String[]{file.getPath()},
                                    null, new MediaScannerConnection.OnScanCompletedListener() {
                                        public void onScanCompleted(String path, Uri uri) {

                                        }});

                        }
                    };
                    final File file =CommonUtils.createFile("partener_qr_code.png");

                    actionSheetDialog = new ActionSheetDialog(ShowWebView.this, new String[]{"保存二维码图片"}, null);
                    actionSheetDialog.isTitleShow(false).itemTextColor(Color.parseColor("#404040")).cornerRadius(4)
                            .show();
                    actionSheetDialog.setOnOperItemClickL(new OnOperItemClickL() {
                        @Override
                        public void onOperItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
                            switch (position) {
                                case 0:
                                    aq.download(codeUrl,file,cb);
                                    break;

                            }
                            actionSheetDialog.dismiss();
                        }
                    });
                }
            });
        }
        @JavascriptInterface
        public void BecomeP() {
            handler.post(new Runnable() {
                public void run() {
                    aq = new AQuery(ShowWebView.this);

                    aq.progress(new AQProgressDialog(ShowWebView.this)).ajax(partner_notify_money, JSONObject.class,
                            new AjaxCallback<JSONObject>() {

                                @Override
                                public void callback(String url, JSONObject obj,
                                                     AjaxStatus status) {
                                    // TODO Auto-generated method stub
                                    if (status.getCode() == -101) {
                                        Toast.makeText(ShowWebView.this, "网络异常,请检查网络", Toast.LENGTH_SHORT);
                                        return;
                                    }
                                    if (status.getCode() != 200) {
                                        Toast.makeText(ShowWebView.this, "网络异常:" + status.getCode(), Toast.LENGTH_SHORT).show();
                                    } else {
                                        try {
                                            if (obj.getBoolean("isSuccess")) {

                                                dialog = new BuyPartnerDialog(ShowWebView.this, new DialogListener() {
                                                    @Override
                                                    public void onApply(JSONObject obj, String clazz) {
                                                        ShowWebView.this.type = clazz;
                                                        try {
                                                            if (Integer.valueOf(clazz) == BuyPointsDialog.PAYMENT_TYPE_ALIPAY) {
                                                                String a = getJsonArray(obj, "errors").getString(0);
                                                                String[] array = a.split("&");
                                                                for (String temp : array) {
                                                                    if (temp.contains("out_trade_no")) {
                                                                        String no = temp.split("=")[1];
                                                                        ShowWebView.this.outtradeno = no.substring(1, no.length() - 1);
                                                                    }
                                                                }
                                                                pay(a);

                                                            } else {
                                                                wechatPay(new JSONObject(getJsonArray(obj, "errors").getString(0)));
                                                            }
                                                        } catch (JSONException e) {
                                                            e.printStackTrace();
                                                        }
                                                        dialog.dismiss();
                                                    }

                                                    @Override
                                                    public void onCancel() {
                                                        dialog.dismiss();
                                                    }
                                                }, Integer.valueOf(getJsonArray(obj, "errors").getString(0)), mobile);
                                                dialog.show();
                                            } else {
                                                Toast.makeText(aq.getContext(),
                                                        obj.getString("errors"),
                                                        Toast.LENGTH_SHORT).show();
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                    }
                                }

                            });

                }
            });


        }
    }

    public void wechatPay(JSONObject json) {

        // String url =
        // "http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=android";
        try {
            if (null != json && !json.has("retcode")) {
                PayReq req = new PayReq();
                // req.appId = "wxf8b4f85f3a794e77"; // 测试用appId

                req.appId = json.getString("appid");

                req.partnerId = json.getString("partnerid");
                req.prepayId = json.getString("prepayid");
                this.outtradeno = req.prepayId;
                req.nonceStr = json.getString("noncestr");
                req.timeStamp = json.getString("timestamp");
                req.packageValue = "Sign=WXPay";
                req.sign = json.getString("sign");
                req.extData = "app data"; // optional
                // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                IWXAPI wxApi = WXAPIFactory.createWXAPI(aq.getContext(),
                        req.appId, true);
                wxApi.registerApp(req.appId);
                if (!wxApi.isWXAppInstalled()) {
                    Toast.makeText(aq.getContext(), "没有安装微信",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!wxApi.isWXAppSupportAPI()) {
                    Toast.makeText(aq.getContext(), "当前版本不支持支付功能",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                wxApi.sendReq(req);
            } else {
                Toast.makeText(aq.getContext(),
                        "返回错误" + json.getString("retmsg"), Toast.LENGTH_SHORT)
                        .show();
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;

    public void pay(final String payInfo) {
        /**
         * 完整的符合支付宝参数规范的订单信息
         */

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(ShowWebView.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String payment_status = "";
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
//					Log.d("sort", "resultInfo" + resultInfo);
//					Log.d("sort", "resultStatus" + resultStatus);
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        payment_status = WXPayEntryActivity.ALI_PAY_SUCCESS;
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            payment_status = WXPayEntryActivity.ALI_PAY_SUCCESS;
                        } else {
                            payment_status = WXPayEntryActivity.ALI_PAY_FAILURE;
                        }


                    }

                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(aq.getContext(), "检查结果为：" + msg.obj,
                            Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
            Intent intent = new Intent();
            intent.setAction(WXPayEntryActivity.PAY_FINISH);
            intent.putExtra("state", payment_status);
            aq.getContext().sendOrderedBroadcast(intent, null);
        }
    };


    /**
     * 配置分享平台参数</br>
     */
    private void configPlatforms() {
        // 添加新浪SSO授权
        mController.getConfig().setSsoHandler(new SinaSsoHandler());

        // 添加微信、微信朋友圈平台
        addWXPlatform();
    }


    /**
     * @return
     * @功能描述 : 添加微信平台分享
     */
    private void addWXPlatform() {
        // 注意：在微信授权的时候，必须传递appSecret
        // wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
        String appId = "wxe94f6ebf0daa4bda";
        String appSecret = "e2f4f10444b6399f18e151737a0b653e";
        // 添加微信平台
        UMWXHandler wxHandler = new UMWXHandler(ShowWebView.this, appId, appSecret);
        wxHandler.addToSocialSDK();

        // 支持微信朋友圈
        UMWXHandler wxCircleHandler = new UMWXHandler(ShowWebView.this, appId, appSecret);
        wxCircleHandler.setToCircle(true);
        wxCircleHandler.addToSocialSDK();
    }

    /**
     * 根据不同的平台设置不同的分享内容</br>
     */
    private void setShareContent() {
        // 配置SSO
//        mController.getConfig().setSsoHandler(new SinaSsoHandler());
        UMImage localImage = new UMImage(ShowWebView.this, R.drawable.appicon);
//
        WeiXinShareContent weixinContent = new WeiXinShareContent();
        weixinContent.setShareContent(Constants.SHARE_PROXINFO);
        weixinContent.setTitle(Constants.SHARE_PROXTITLE);
        weixinContent.setTargetUrl(webhost + "/Home/Share/proxy/pid/" + pref.proxyID().get());
        weixinContent.setShareMedia(localImage);
        mController.setShareMedia(weixinContent);

        // 设置朋友圈分享的内容
        CircleShareContent circleMedia = new CircleShareContent();
        circleMedia.setShareContent(Constants.SHARE_PROXTITLE);
        circleMedia.setTitle(Constants.SHARE_PROXINFO);
        circleMedia.setShareMedia(localImage);
        circleMedia.setTargetUrl(webhost + "/Home/Share/proxy/pid/" + pref.proxyID().get());
        mController.setShareMedia(circleMedia);
//
        SinaShareContent sinaContent = new SinaShareContent();
        sinaContent.setTitle(Constants.SHARE_PROXTITLE);
        sinaContent.setShareContent(Constants.SHARE_PROXINFO + webhost + "/Home/Share/proxy/pid/" + pref.proxyID().get() + Constants.SHARE_PROXTITLE);
        sinaContent.setShareMedia(localImage);
        sinaContent.setTargetUrl(webhost + "/Home/Share/proxy/pid/" + pref.proxyID().get());
        mController.setShareMedia(sinaContent);


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }


    }


}



